package edu.ccut.saturn.web.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import edu.ccut.saturn.component.ComponentFactory;
import edu.ccut.saturn.component.ComponentManager;
import edu.ccut.saturn.component.IComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnComponentException;
import edu.ccut.saturn.component.SaturnLoggerManager;

public class SaturnLoggerListener implements ServletContextListener {

	private static final String LOGGER_KEY = "saturnManager::/logic/QueryPerLoggerKeyLogic.logic";

	private static final String LOGGER_KEY_BUNDLE_MANAGER = SaturnLoggerManager.LOGGER_KEY_BUNDLE_SERVICE;

//	private static final String LOGGER_KEY_LOAD_BUNDLE_CONFIG = SaturnLoggerManager.LOGGER_KEY_LOAD_BUNDLE_CONFIG;

	private static final String LOGGER_KEY_BUNDLE_RUNTIME = SaturnLoggerManager.LOGGER_KEY_COMPONENT_RUNTIME;

	private static final String LOGGER_KEY_LOAD_BUNDLE = SaturnLoggerManager.LOGGER_KEY_LOAD_BUNDLE;

	public void contextDestroyed(ServletContextEvent arg0) {
	}

	public void contextInitialized(ServletContextEvent arg0) {
		try {
			String runTimeLevel = getLoggerLevel(LOGGER_KEY_BUNDLE_RUNTIME);
			String managerLevel = getLoggerLevel(LOGGER_KEY_BUNDLE_MANAGER);
		//	String configLevel = getLoggerLevel(LOGGER_KEY_LOAD_BUNDLE_CONFIG);
			String bundleLevel = getLoggerLevel(LOGGER_KEY_LOAD_BUNDLE);

			if (runTimeLevel != null && managerLevel != null
					&& bundleLevel != null) {
				SaturnLoggerManager.getInstance().getSaturnLogger(
						LOGGER_KEY_BUNDLE_RUNTIME).setLevel(runTimeLevel);
				SaturnLoggerManager.getInstance().getSaturnLogger(
						LOGGER_KEY_BUNDLE_MANAGER).setLevel(managerLevel);
//				SaturnLoggerManager.getInstance().getSaturnLogger(
//						LOGGER_KEY_LOAD_BUNDLE_CONFIG).setLevel(configLevel);
				SaturnLoggerManager.getInstance().getSaturnLogger(
						LOGGER_KEY_LOAD_BUNDLE).setLevel(bundleLevel);
			}
		} catch (SaturnComponentException e) {
			e.printStackTrace();
		}
	}

	private String getLoggerLevel(String keyId) throws SaturnComponentException {
		IParameterContext parameterContext = null;
		String level = null;

		IComponent component = ComponentManager.getInstance().getComponent(
				LOGGER_KEY);
		if (component != null) {
			parameterContext = ComponentFactory.createParameterContext();

			parameterContext.addParameter(keyId, String.class);
			parameterContext.addParameter(null, String.class);

			try {
				component.execute(parameterContext);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			level = (String) parameterContext.getParameterValue(1);
			if (level == null) {
				throw new SaturnComponentException(
						"Can not obtain logger level.");
			}
		}

		return level;
	}
}
